from logging import getLogger

from django.http import Http404
from django.shortcuts import get_object_or_404, render_to_response

from meercat.ui.client.utils import handleUrlParams
from meercat.ui.django.models import Search, Resource



log = getLogger('meercat.ui.django.views')

def search(request, identifier, **kwargs):
    kwargs.setdefault('template_name','meercat/search.html')
    kwargs.setdefault('ajax_template_name',None)
    kwargs.setdefault('template_object_name', 'search')
    kwargs.setdefault('extra_context',{})
    kwargs.setdefault('mimetype',None)
    
    search = get_object_or_404(Search, identifier=identifier)
    
    c = {}
    params = {}
    
    c[kwargs['template_object_name']] = search
    
    if 'q' in request.REQUEST:
        params['q'] = request.REQUEST['q']
    
    if 'rows' in request.REQUEST:
        try:
            params['rows'] = int(request.REQUEST['rows'])
        except:
            log.debug('Error parsing number of rows: %s' % (str(request.REQUEST['rows']),))
    
    c['response'] = search.query(**params)
    
    try:
        page = int(request.REQUEST.get('page',1))
        assert page > 0
    except:
        page = 1
    
    try:
        c['paginator'] = c['response'].paginator
        c['page'] = c['paginator'].page(page)
        if c['page'].has_next():
            c['next_page'] = '%s?%s' % (request.path,
                                        handleUrlParams(dict(request.GET.iterlists()),
                                                        _replace=True,
                                                        page=c['page'].next_page_number()),)
    except:
        log.exception('blah')
        c['paginator'] = None
        c['page'] = None
    
    try:
        if c['page'].has_next():
            c['next_page'] = '%s?%s' % (request.path,
                                        handleUrlParams(dict(request.GET.iterlists()),
                                                        _replace=True,
                                                        page=c['page'].next_page_number()),)
    except:
        log.exception('blah')
        c['next_page'] = None
    
    kwargs['extra_context'].update(c)
    
    if request.is_ajax() and kwargs['ajax_template_name']:
        kwargs['template_name'] = kwargs['ajax_template_name']
    
    return render_to_response(kwargs['template_name'], kwargs['extra_context'],
                              mimetype=kwargs['mimetype'])
    


def resource(request, identifier, **kwargs):
    kwargs.setdefault('template_name','meercat/resource.html')
    kwargs.setdefault('ajax_template_name',None)
    kwargs.setdefault('extra_context', {})
    kwargs.setdefault('template_object_name', 'resource')
    kwargs.setdefault('mimetype',None)
    
    try:
        resource = Resource(identifier)
    except:
        log.exception('Error getting the resource')
        raise Http404('Resource does not exist')
    
    kwargs['extra_context'][kwargs['template_object_name']] = resource
    
    if request.is_ajax() and kwargs['ajax_template_name']:
        kwargs['template_name'] = kwargs['ajax_template_name']
    
    return render_to_response(kwargs['template_name'], kwargs['extra_context'],
                              mimetype=kwargs['mimetype'])
